layui.use('form', function() {
    var form = layui.form;
    var layer = layui.layer;

    var randerOneItem = [
        { name: '菜单名称', id: 'name', type: 'text' },
        { name: '菜单图标', id: 'treeIcon', type: 'text' },
        {
            name: '菜单类型',
            id: 'type',
            type: 'select',
            score: [
                { text: '请选择', id: '' },
                { text: '系统', id: '10' },
                { text: '菜单组', id: '20' },
                { text: '菜单模块', id: '30' },
                { text: '快捷报表', id: '40' },
                { text: '功能按钮', id: '90' },
            ]
        },
        { name: '请求地址', id: 'urlAddress', type: 'text' },
        { name: '工程名称', id: 'systemName', type: 'text' },
        {
            name: '本公司系统',
            id: 'hbsoftSystemFlag',
            type: 'select',
            score: [
                { text: '是', id: '0' },
                { text: '否', id: '1' }
            ]
        },
        { name: '数据库名称', id: 'databaseName', type: 'text' },
        { name: '系统简介', id: 'remarks', type: 'textarea' },
    ]

    var randerTwoItem = [
        { name: '菜单名称', id: 'name', type: 'text' },
        { name: '菜单图标', id: 'treeIcon', type: 'text' },
        {
            name: '菜单类型',
            id: 'type',
            type: 'select',
            score: [
                { text: '请选择', id: '' },
                { text: '系统', id: '10' },
                { text: '菜单组', id: '20' },
                { text: '菜单模块', id: '30' },
                { text: '快捷报表', id: '40' },
                { text: '功能按钮', id: '90' },
            ]
        },
        { name: '左边距', id: 'left', type: 'number' },
        { name: '上边距', id: 'top', type: 'number' }
    ]

    var randerThreeItem = [
        { name: '菜单名称', id: 'name', type: 'text' },
        { name: '菜单图标', id: 'treeIcon', type: 'text' },
        {
            name: '菜单类型',
            id: 'type',
            type: 'select',
            score: [
                { text: '请选择', id: '' },
                { text: '系统', id: '10' },
                { text: '菜单组', id: '20' },
                { text: '菜单模块', id: '30' },
                { text: '快捷报表', id: '40' },
                { text: '功能按钮', id: '90' },
            ]
        },
        { name: '请求地址', id: 'urlAddress', type: 'text' },
        { name: '左边距', id: 'left', type: 'number' },
        { name: '上边距', id: 'top', type: 'number' }
    ]

    getTreeData()

    $('#addSame').click(function() {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getSelectedNodes()[0];
        var father = nodes.getParentNode()
        father = JSON.stringify(father)
        $('#save').attr('data-father', father)
        $('#idPrikey').val(0)
        if (nodes.id.length == 3) {
            rander(randerOneItem)
        } else if (nodes.id.length == 6) {
            rander(randerTwoItem)
        } else if (nodes.id.length == 9) {
            rander(randerThreeItem)
        }
        form.render();
        open()
    });

    $("#addNext").click(function() {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getSelectedNodes()[0];

        $('#idPrikey').val(0)
        if (nodes.id.length == 3) {
            rander(randerTwoItem)
        } else if (nodes.id.length == 6) {
            rander(randerThreeItem)
        } else if (nodes.id.length == 9) {
            layer.alert('该节点不可添加下级');
        }
        form.render();
        open()

        nodes = JSON.stringify(nodes)
        $('#save').attr('data-father', nodes)
    })

    $("#cancel").click(function() {
        close()
    });

    $("#edit").click(function() {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getSelectedNodes()[0];

        nodes = JSON.stringify(nodes)
        $('#save').attr('data-father', nodes)

        $('#idPrikey').val(1)
        open()
    })

    $("#save").click(function() {
        var data = {}
        var nodes = $(this).attr('data-father')
        nodes = JSON.parse(nodes)

        $('.keyInput').each(function() {
            var key = $(this).attr('id')
            var text = $(this).parents('.layui-form-item').find('.layui-form-label').text()
            var val = $(this).val()
            data[key] = $(this).val()

        })

        data.id_prikey = $('#idPrikey').val()
        if (nodes) {
            data.pId = nodes.id
        }
        if (data.id_prikey == 1) {
            data.id_prikey = $("#id_prikey").val()
            data.id = nodes.id
        }
        save(data)
    })






    // getCaption(fontStr);




    $("#del").click(function() {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getSelectedNodes()[0];
        var id = nodes.id
        $.ajax({
            url: "removeMenu",
            type: "POST",
            data: {
                id: id
            },
            success: function(res) {
                if (res.code == 0) {
                    layer.alert(res.message, function() {
                        // getTreeData()
                        layer.closeAll();
                        treeObj.removeNode(nodes);
                    });
                } else {
                    layer.alert(res.message);
                }
            }
        });
    })



    function save(data) {

        var keyArr = []
        for (var key in data) {
            keyArr.push(key)
        }
        for (var i = 0; i < keyArr.length; i++) {
            if (data[keyArr[i]] == '') {
                layer.alert('所有保存项不能为空');
                return false
            }
        }


        var flag = data.id_prikey
        if (flag == 0) {
            var url = 'addMenu'
        } else {
            var url = 'setMenu'
        }
        $.ajax({
            url: url,
            type: "POST",
            data: data,
            success: function(res) {
                if (res.code == 0) {
                    layer.alert(res.message, function() {
                        getTreeData()
                        layer.closeAll();
                        close()
                        openFather()
                    });
                } else {
                    layer.alert(res.message);
                }
            }
        });
    }

    function openFather() {
        var nodes = $("#save").attr('data-father')
        nodes = JSON.parse(nodes)

        setTimeout(function() {
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            treeObj.expandNode(nodes, true, true, true);
        }, 2000)

    }

    function close() {
        $('.hb-mask').show()
        $("#addSame").removeClass('layui-btn-disabled')
        $("#addNext").removeClass('layui-btn-disabled')
        $("#edit").removeClass('layui-btn-disabled')
        $("#del").removeClass('layui-btn-disabled')
        $("#cancel").addClass('layui-btn-disabled')
        $("#save").addClass('layui-btn-disabled')

        $("#addSame").attr('disabled', false)
        $("#addNext").attr('disabled', false)
        $("#edit").attr('disabled', false)
        $("#del").attr('disabled', false)
        $("#cancel").attr('disabled', true)
        $("#save").attr('disabled', true)
    }

    function open() {
        $('.hb-mask').hide()
        $("#addSame").addClass('layui-btn-disabled')
        $("#addNext").addClass('layui-btn-disabled')
        $("#del").addClass('layui-btn-disabled')
        $("#edit").addClass('layui-btn-disabled')
        $("#cancel").removeClass('layui-btn-disabled')
        $("#save").removeClass('layui-btn-disabled')

        $("#addSame").attr('disabled', true)
        $("#addNext").attr('disabled', true)
        $("#edit").attr('disabled', true)
        $("#del").attr('disabled', true)
        $("#cancel").attr('disabled', false)
        $("#save").attr('disabled', false)

    }


    function getTreeData() {
        var setting = {
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onClick: function() {
                    var treeObj = $.fn.zTree.getZTreeObj("tree");
                    var nodes = treeObj.getSelectedNodes();
                    getTreeDetail(nodes[0].id)
                    close()

                }
            }
        };
        $.ajax({
            url: "getTreeMenu",
            type: "POST",
            data: {},
            success: function(res) {

                $.fn.zTree.init($("#tree"), setting, res.data);

                var zTree = $.fn.zTree.getZTreeObj("tree");
                var node = zTree.getNodeByParam('id', '003');

                zTree.selectNode(node);
                zTree.setting.callback.onClick(null, zTree.setting.treeId, node);
            }
        });
    }

    function after(obj, str) {
        var index = obj.lastIndexOf(str);
        obj = obj.substring(index + 1, obj.length);
        return obj;
    }

    function getTreeDetail(id) {
        $.ajax({
            url: "getMenuById",
            type: "POST",
            data: {
                id: id
            },
            success: function(res) {
                var data = res.data
                $('#addNext').removeClass('layui-btn-disabled')
                $("#addNext").attr('disabled', false)
                if (id.length == 3) {
                    var formArr = randerOneItem
                } else if (id.length == 6) {
                    var formArr = randerTwoItem
                } else if (id.length == 9) {
                    $('#addNext').addClass('layui-btn-disabled')
                    $("#addNext").attr('disabled', true)
                    var formArr = randerThreeItem
                }
                rander(formArr, data)
                form.render();
            }
        });
    }

    function rander(formArr, data) {
        var html = ''
        for (var i = 0; i < formArr.length; i++) {
            html += '<div class="layui-form-item layui-form-pane" pane>'
            html += '    <label class="layui-form-label">' + formArr[i].name + ':</label>'
            html += '    <div class="layui-input-block">'
            if (formArr[i].type == 'text') {
                if (formArr[i].name == '菜单图标') {
                    html += '       <input type="text" style="width:80%;float:left;margin-right:15px" id="' + formArr[i].id + '" placeholder="请输入' + formArr[i].name + '" autocomplete="off" class="layui-input keyInput">'
                    html += '       <button class="layui-btn layui-btn-sm" id="selectIcon">选择图标</button>'
                } else {
                    html += '     <input type="text" id="' + formArr[i].id + '" placeholder="请输入' + formArr[i].name + '" autocomplete="off" class="layui-input keyInput">'
                }
            } else if (formArr[i].type == 'select') {
                html += '     <select id="' + formArr[i].id + '" class="keyInput">'
                for (var s = 0; s < formArr[i].score.length; s++) {
                    html += '         <option value="' + formArr[i].score[s].id + '">' + formArr[i].score[s].text + '</option>'
                }
                html += '     </select>'
            } else if (formArr[i].type == 'textarea') {
                html += '<textarea id="' + formArr[i].id + '" placeholder="请输入内容" class="layui-textarea keyInput"></textarea>'
            } else if (formArr[i].type == 'number') {
                html += '     <input type="number" id="' + formArr[i].id + '" placeholder="请输入' + formArr[i].name + '" autocomplete="off" class="layui-input keyInput">'
            }
            html += '    </div>'
            html += '</div>'
        }
        $('#list').html(html)

        assignment(data)

        $("#selectIcon").click(function() {

            var htmlIcon = ''
            htmlIcon += '<div class="iconOut" id="iconList">'
            htmlIcon += '    <ul>'
            htmlIcon += '        <li></li>'
            htmlIcon += '    </ul>'
            htmlIcon += '</div>'


            layer.open({
                type: 1,
                content: htmlIcon,
                area: ['500px', '500px'],
                title: '选择图标'
            });



            getIcon()
        })



    }

    function getIcon() {
        var link = document.getElementById('font');
        var xhr = new XMLHttpRequest();
        xhr.open("GET", link.href)
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr)
                var str = after(xhr.responseText, '.fa-glass:before{')
                str = str.split('.')
                var classArr1 = []
                for (var i = 0; i < str.length; i++) {
                    classArr1.push(str[i].split('{')[0])
                }

                var classArr2 = []
                for (var i = 0; i < classArr1.length; i++) {
                    classArr2.push(classArr1[i].split(':')[0])
                }
                var html = ''
                for (var i = 0; i < classArr2.length; i++) {
                    if (classArr2[i].length < 20) {
                        if (classArr2[i].split('fa-')[1]) {
                            html += '<li>'
                            html += '    <h1><span class="fa ' + classArr2[i] + ' fa-fw"></span></h1>'
                            html += '    <h2>' + classArr2[i].split('fa-')[1] + '</h2>'
                            html += '</li>'
                        }

                    }
                }
                $("#iconList ul").html(html)

                $("#iconList li").click(function() {
                    var classStr = $(this).find('span').attr('class')
                    $("#treeIcon").val(classStr)
                    layer.closeAll();
                });
            }
        }
        xhr.send();



    }

    function assignment(data) {
        var keyArr = []
        for (var key in data) {
            keyArr.push(key)
        }
        for (var i = 0; i < keyArr.length; i++) {
            $('#' + keyArr[i]).val(data[keyArr[i]])
        }

    }
})